import 'package:flutter/material.dart';
import 'package:wechat/const.dart';
import 'package:wechat/pages/discover/discover_child_page.dart';
import 'package:wechat/pages/friends/index_bar.dart';

import 'friends_data.dart';

class _FriendCell extends StatelessWidget {
  _FriendCell({this.imageUrl, this.name = '', this.groupTitle, this.imageAssets});

  final String? imageUrl;
  final String name;// 必填字段
  final String? groupTitle;
  final String? imageAssets;
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          alignment: Alignment.centerLeft,
          padding: EdgeInsets.only(left: 10),
          height: groupTitle != null ? 30 : 0,
          color: WeChatThemeColor,
          child: groupTitle != null
              ? Text(
                  groupTitle!,
                  style: TextStyle(color: Colors.grey),
                )
              : null,
        ), //头部
        Container(
          color: Colors.white,
          child: Row(
            children: [
              Container(
                margin: EdgeInsets.all(10),
                width: 34,
                height: 34,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(6.0),
                    image: DecorationImage(
                      image: imageUrl != null
                          ? NetworkImage(imageUrl!)
                          : (AssetImage(imageAssets ?? '') as ImageProvider),
                    )),
              ), //图片
              Container(
                // color: Colors.red,
                width: screenWidth(context) - 54,
                child: Column(
                  children: [
                    Container(
                      alignment: Alignment.centerLeft,
                      height: 54,
                      child: Text(
                        name,
                        style: TextStyle(fontSize: 18),
                      ),
                    ),
                    Container(
                      height: 0.5,
                      color: WeChatThemeColor,
                    ), //下划线
                  ],
                ),
              ), //昵称+下划线
            ],
          ),
        ), //Cell的内容
      ],
    );
  }
}

class FriendsPage extends StatefulWidget {
  @override
  _FriendsPageState createState() => _FriendsPageState();
}

class _FriendsPageState extends State<FriendsPage>
    with AutomaticKeepAliveClientMixin<FriendsPage> {
  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  double _cellHeight = 54.5;
  double _groupHeight = 30.0;

  //字典，里面放item和高度的对应的数据。
  final Map _groupOffsetMap = {
    INDEX_WORDS[0]: 0.0,
    INDEX_WORDS[1]: 0.0,
  };

  final List<Friends> _headerData = [
    Friends(imageAssets: 'images/新的朋友.png', name: '新的朋友'),
    Friends(imageAssets: 'images/群聊.png', name: '群聊'),
    Friends(imageAssets: 'images/标签.png', name: '标签'),
    Friends(imageAssets: 'images/公众号.png', name: '公众号'),
  ];
  final List<Friends> _listDatas = [];
  ScrollController _scrollController = ScrollController();
  @override
  void initState() {
    super.initState();

    _scrollController = ScrollController();
    //创建数据
    _listDatas
      ..addAll(datas)
      ..addAll(datas);
    //排序
    _listDatas.sort((Friends a, Friends b) {
      return (a.indexLetter ?? '').compareTo(b.indexLetter ?? '');
    });
    var _groupOffset = _cellHeight * _headerData.length;
    //进过循环计算，将每一个头的位置算出来。放入字典
    for (int i = 0; i < _listDatas.length; i++) {
      if (i < 1) {
        //第一个cell一定有头！
        _groupOffsetMap.addAll({_listDatas[i].indexLetter: _groupOffset});
        //保存完了再加_groupOffset
        _groupOffset += _cellHeight + _groupHeight;
      } else if (_listDatas[i].indexLetter == _listDatas[i - 1].indexLetter) {
        //不同存，只需要加Cell的高度
        _groupOffset += _cellHeight;
      } else {
        _groupOffsetMap.addAll({_listDatas[i].indexLetter: _groupOffset});
        //保存完了再加_groupOffset
        _groupOffset += _cellHeight + _groupHeight;
      }
    }
  }

  Widget _itemForRow(BuildContext context, int index) {
    //显示头部4个Cell
    if (index < _headerData.length) {
      return _FriendCell(
        imageAssets: _headerData[index].imageAssets,
        name: _headerData[index].name ?? '',
      );
    }
    //是否显示组名字！
    bool _hiddenIndexLetter = (index - 4 > 0 &&
        _listDatas[index - 4].indexLetter == _listDatas[index - 5].indexLetter);

    return _FriendCell(
      imageUrl: _listDatas[index - 4].imageUrl,
      name: _listDatas[index - 4].name ?? '',
      groupTitle: _hiddenIndexLetter ? null : _listDatas[index - 4].indexLetter,
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
        appBar: AppBar(
          actions: [
            GestureDetector(
              onTap: () {
                Navigator.of(context).push(MaterialPageRoute(
                    builder: (BuildContext context) => DiscoverChildPage(
                          title: '添加朋友',
                        )));
              },
              child: Container(
                margin: EdgeInsets.only(right: 10),
                child: Image(
                  image: AssetImage('images/icon_friends_add.png'),
                  width: 25,
                ),
              ),
            ),
          ],
          backgroundColor: WeChatThemeColor,
          title: Text('通讯录'),
        ),
        body: Stack(
          children: [
            Container(
              color: WeChatThemeColor,
              child: ListView.builder(
                controller: _scrollController,
                itemBuilder: _itemForRow,
                itemCount: _listDatas.length + _headerData.length,
              ),
            ), //列表
            IndexBar((String str) {
                if (_groupOffsetMap[str] != null) {
                  // 获取最大滚动范围
                  double max = _scrollController.position.maxScrollExtent;
                  double toOffset = _groupOffsetMap[str] > max ? max : _groupOffsetMap[str];
                  _scrollController.animateTo(toOffset,
                      duration: Duration(microseconds: 100),
                      curve: Curves.easeIn);
                }
              },
            ), //悬浮的索引条
          ],
        ));
  }
}

const INDEX_WORDS = [
  '🔍',
  '☆',
  'A',
  'B',
  'C',
  'D',
  'E',
  'F',
  'G',
  'H',
  'I',
  'J',
  'K',
  'L',
  'M',
  'N',
  'O',
  'P',
  'Q',
  'R',
  'S',
  'T',
  'U',
  'V',
  'W',
  'X',
  'Y',
  'Z'
];
